import { StringUtil } from './StringUtil'

export const CurrencyUtil = {
    /**
     * 金额转汉字大写
     * @returns {trim}
     */
    moneyFormatInWords (num) {
        if (!num) return ''
        let sign = ''
        if (num < 0) {
            sign = '负'
            num = Math.abs(num)
        }
        let strOutput = ''
        let strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分'
        num += '00'
        const intPos = num.indexOf('.')
        if (intPos >= 0) { num = num.substring(0, intPos) + num.substr(intPos + 1, 2) }
        strUnit = strUnit.substr(strUnit.length - num.length)
        for (let i = 0; i < num.length; i++) {
            strOutput += '零壹贰叁肆伍陆柒捌玖'.substr(num.substr(i, 1), 1) +
                strUnit.substr(i, 1)
        }
        return sign + strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零').replace(
            /零{2,}/g, '零').replace(/零([亿|万])/g, '$1').replace(/零+元/, '元')
            .replace(/亿零{0,3}万/, '亿').replace(/^元/, '零元')
    },
    /**
     * 金额格式化
     * @param value 金额
     * @param _currency 货币符号
     * @param quartile 千分位
     * @param decimals 精度
     * @returns {string}
     */
    format (value, quartile, _currency, decimals) {
        if (!value) return ''
        value = StringUtil.toFixed(value) // 格式化精度
        const valueStr = ('' + value)
        let decimalLength = 0
        const decimalIndex = valueStr.lastIndexOf('.')
        if (decimalIndex > 0) decimalLength = valueStr.split('.')[1].length
        value = parseFloat(value)
        if (!isFinite(value)) return ''
        _currency = _currency != null ? _currency : ''// 默认不带货币符号
        decimals = !decimals ? decimalLength : decimals

        const stringified = parseFloat(Math.abs(value).toFixed(decimals)).toString()
        const reg = /\B(?=(\d{3})+(?!\d))/g
        const currencyValue = stringified.replace(reg, ',')
        const sign = value < 0 ? '-' : ''

        return `${sign}${_currency}${quartile ? currencyValue : stringified}`
    }
}
